package Model;

import java.nio.ByteBuffer;
import java.util.Map;

public class Data 
{
	
	private final byte[] NO_DATA_PULL = null;
	
	// eager initialization is both thread safe and will also load the data from db
	private static volatile Data instance = new Data();
	
	private Map<ByteBuffer, Messages> m_Data;
	private DB m_Db;
	
	private Data()
	{
		// load previous state from database
		m_Db = new DB();
		m_Data = m_Db.load();	
	}
	
		
	public static Data getInstance()
	{
		return instance;
	}		
	
	public byte[] pull(byte[] token, int index)
	{		
		Messages msgs = null;
		
		if(index > -1)
		{
			msgs = m_Data.get(ByteBuffer.wrap(token));
		}
		
		if (msgs == null)
		{
			return NO_DATA_PULL;
		}
				
		return msgs.pull(index);
	}
	
	public void push(byte[] token, byte[] msg)
	{
		ByteBuffer tokenWrapper = ByteBuffer.wrap(token);
		Messages msgs = m_Data.get(tokenWrapper);
		
		if (msgs == null)
		{
			msgs = new Messages();
			m_Data.put(tokenWrapper, msgs);
		}
				
		int index = msgs.append(msg);
		
		m_Db.append(token, msg, index);
	}

	

}
